In [6]:
# ================================================================
# LAB 11. MULTICOLLINEARITY AND RIDGE REGRESSION
#
# STAT 415/615 - Regression
#
# Topics:
#   1. Measuring multicollinearity
#      - Correlations
#      - Variance inflation factors (VIF)
#      - Generalized VIF for categorical predictors
#
#   2. Ridge regression
#      - Fitting a ridge regression model
#      - Ridge coefficient paths
#      - Generalized cross-validation (GCV)
#      - Selecting the penalty parameter lambda
#      - Prediction with ridge regression
#
# ================================================================


# ================================================================
# PART 0. PREPARATION
# ================================================================

# Import the required libraries.
#
# pandas: data manipulation
# numpy: numerical calculations
# statsmodels: ordinary least-squares regression and VIF
# sklearn: ridge regression and standardization
# matplotlib: graphs

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import statsmodels.api as sm

from statsmodels.stats.outliers_influence import (
    variance_inflation_factor
)

from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler


# Load the mtcars dataset.
#
# mtcars is included in R but not directly in sklearn.
# We load the same dataset from the Rdatasets collection.
#
# The first column contains automobile names.

mtcars = pd.read_csv(
    "https://raw.githubusercontent.com/vincentarelbundock/"
    "Rdatasets/master/csv/datasets/mtcars.csv",
    index_col=0
)

# Examine the variable names.

print("VARIABLE NAMES")
print(mtcars.columns.tolist())

# Examine the first observations.

print("\nFIRST OBSERVATIONS")
print(mtcars.head())
VARIABLE NAMES
['mpg', 'cyl', 'disp', 'hp', 'drat', 'wt', 'qsec', 'vs', 'am', 'gear', 'carb']

FIRST OBSERVATIONS
                    mpg  cyl   disp   hp  drat     wt   qsec  vs  am  gear  \
rownames                                                                     
Mazda RX4          21.0    6  160.0  110  3.90  2.620  16.46   0   1     4   
Mazda RX4 Wag      21.0    6  160.0  110  3.90  2.875  17.02   0   1     4   
Datsun 710         22.8    4  108.0   93  3.85  2.320  18.61   1   1     4   
Hornet 4 Drive     21.4    6  258.0  110  3.08  3.215  19.44   1   0     3   
Hornet Sportabout  18.7    8  360.0  175  3.15  3.440  17.02   0   0     3   

                   carb  
rownames                 
Mazda RX4             4  
Mazda RX4 Wag         4  
Datsun 710            1  
Hornet 4 Drive        1  
Hornet Sportabout     2  
In [7]:
# ================================================================
# PART 1. MEASURING MULTICOLLINEARITY
# ================================================================

# Multicollinearity occurs when two or more predictors
# are strongly related to each other.
#
# It can make individual regression coefficients unstable
# and increase their standard errors.
#
# A useful first step is to examine correlations
# among the variables.


# ------------------------------------------------
# 1A. Correlation matrix
# ------------------------------------------------

# corr() calculates the Pearson correlation coefficient
# for every pair of numerical variables.
#
# Correlations close to +1 or -1 indicate strong
# linear relationships.

print("\nCORRELATION MATRIX")

print(mtcars.corr().round(3))


# ------------------------------------------------
# 1B. Variance inflation factors
# ------------------------------------------------

# Variance inflation factors (VIF) measure how strongly
# each predictor is linearly related to the other predictors.
#
# For predictor Xj:
#
#                1
#     VIFj = ----------
#             1 - Rj^2
#
# where Rj^2 is obtained by regressing Xj on all the
# other predictors.
#
# A VIF of 1 indicates no linear association with
# the other predictors.
#
# Large VIF values indicate substantial multicollinearity.
#
# Values above 5 or 10 are often used as informal
# warning thresholds, not strict statistical rules.


# Fit the full regression:
#
# mpg = beta0 + beta1*cyl + ... + beta10*carb + error

Y = mtcars["mpg"]

X = mtcars.drop(columns="mpg")

X1 = sm.add_constant(X)

reg = sm.OLS(Y, X1).fit()


# Calculate VIF for each predictor.
#
# The intercept is excluded from the VIF table.

vif = pd.Series(
    [
        variance_inflation_factor(X1.values, j)
        for j in range(1, X1.shape[1])
    ],
    index=X.columns,
    name="VIF"
)

print("\nVARIANCE INFLATION FACTORS")

print(vif.round(3))


# ------------------------------------------------
# 1C. Generalized VIF for categorical predictors
# ------------------------------------------------

# When a categorical predictor has several categories,
# it is represented by multiple dummy variables.
#
# For example, a variable with three categories requires
# two dummy variables.
#
# Instead of calculating separate VIF values for these
# dummy variables, we can calculate a generalized VIF
# (GVIF) for the entire categorical term.
#
# The adjusted quantity
#
#           GVIF^(1/(2*Df))
#
# accounts for the number of coefficients (Df)
# associated with the term.
#
# For a one-coefficient term, GVIF equals the ordinary VIF.
#
# We use the HOME_SALES dataset from the previous labs.


HOMES = pd.read_csv(
    "https://dr-baron.github.io/415-615/Data/HOME_SALES.csv"
)


# Exclude the response and the observation identifier.

Yhome = HOMES["SALES_PRICE"]

Xhome = HOMES.drop(columns=["ID", "SALES_PRICE"])


# STYLE is a categorical variable even though its
# categories are represented by numbers.

Xhome["STYLE"] = Xhome["STYLE"].astype("category")


# Convert categorical predictors to dummy variables.
#
# drop_first=True removes one category from each group,
# preventing perfect multicollinearity with the intercept.

Xhome = pd.get_dummies(
    Xhome,
    drop_first=True,
    dtype=float
)


# Fit the full regression model.

Xhome1 = sm.add_constant(Xhome)

reg_home = sm.OLS(Yhome, Xhome1).fit()


# ------------------------------------------------
# Calculate generalized VIF
# ------------------------------------------------

# GVIF can be calculated using the correlation matrix
# of the estimated regression coefficients.
#
# For a term represented by a group of coefficients,
#
#                  det(R_term) det(R_other)
#     GVIF = --------------------------------
#                         det(R)
#
# where R is the correlation matrix of all slope
# estimates, excluding the intercept.
#
# For one-coefficient terms, this gives the usual VIF.
#
# The following function groups dummy variables belonging
# to the same original categorical predictor.


def generalized_vif(regression, groups):

    # Covariance matrix of the slope estimates,
    # excluding the intercept.

    V = regression.cov_params().iloc[1:, 1:]

    # Convert covariance matrix to correlation matrix.

    sd = np.sqrt(np.diag(V))

    R = V.div(sd, axis=0).div(sd, axis=1).to_numpy()

    names = list(V.index)

    # Use log-determinants for numerical stability.

    _, logdet_R = np.linalg.slogdet(R)

    results = []

    for term, columns in groups.items():

        idx = [names.index(c) for c in columns]

        other = [
            j for j in range(len(names))
            if j not in idx
        ]

        R_term = R[np.ix_(idx, idx)]
        R_other = R[np.ix_(other, other)]

        _, logdet_term = np.linalg.slogdet(R_term)

        logdet_other = (
            np.linalg.slogdet(R_other)[1]
            if other else 0
        )

        GVIF = np.exp(
            logdet_term + logdet_other - logdet_R
        )

        df = len(idx)

        results.append({
            "Term": term,
            "GVIF": GVIF,
            "Df": df,
            "GVIF^(1/(2*Df))": GVIF ** (1 / (2 * df))
        })

    return pd.DataFrame(results).set_index("Term")


# Group the dummy-variable columns by original predictor.
#
# For example, QUALITY_LOW and QUALITY_MEDIUM
# belong to the same term, QUALITY.

groups = {}

for col in HOMES.drop(columns=["ID", "SALES_PRICE"]).columns:

    if col in Xhome.columns:
        groups[col] = [col]

    else:
        groups[col] = [
            c for c in Xhome.columns
            if c.startswith(col + "_")
        ]


# Calculate generalized VIF.

gvif = generalized_vif(reg_home, groups)

print("\nGENERALIZED VIF")

print(gvif.round(3))
CORRELATION MATRIX
        mpg    cyl   disp     hp   drat     wt   qsec     vs     am   gear  \
mpg   1.000 -0.852 -0.848 -0.776  0.681 -0.868  0.419  0.664  0.600  0.480   
cyl  -0.852  1.000  0.902  0.832 -0.700  0.782 -0.591 -0.811 -0.523 -0.493   
disp -0.848  0.902  1.000  0.791 -0.710  0.888 -0.434 -0.710 -0.591 -0.556   
hp   -0.776  0.832  0.791  1.000 -0.449  0.659 -0.708 -0.723 -0.243 -0.126   
drat  0.681 -0.700 -0.710 -0.449  1.000 -0.712  0.091  0.440  0.713  0.700   
wt   -0.868  0.782  0.888  0.659 -0.712  1.000 -0.175 -0.555 -0.692 -0.583   
qsec  0.419 -0.591 -0.434 -0.708  0.091 -0.175  1.000  0.745 -0.230 -0.213   
vs    0.664 -0.811 -0.710 -0.723  0.440 -0.555  0.745  1.000  0.168  0.206   
am    0.600 -0.523 -0.591 -0.243  0.713 -0.692 -0.230  0.168  1.000  0.794   
gear  0.480 -0.493 -0.556 -0.126  0.700 -0.583 -0.213  0.206  0.794  1.000   
carb -0.551  0.527  0.395  0.750 -0.091  0.428 -0.656 -0.570  0.058  0.274   

       carb  
mpg  -0.551  
cyl   0.527  
disp  0.395  
hp    0.750  
drat -0.091  
wt    0.428  
qsec -0.656  
vs   -0.570  
am    0.058  
gear  0.274  
carb  1.000  

VARIANCE INFLATION FACTORS
cyl     15.374
disp    21.620
hp       9.832
drat     3.375
wt      15.165
qsec     7.528
vs       4.966
am       4.648
gear     5.357
carb     7.909
Name: VIF, dtype: float64

GENERALIZED VIF
                  GVIF  Df  GVIF^(1/(2*Df))
Term                                       
FINISHED_AREA    4.471   1            2.115
BEDROOMS         1.689   1            1.300
BATHROOMS        3.176   1            1.782
GARAGE_SIZE      1.660   1            1.288
YEAR_BUILT       1.942   1            1.394
STYLE            2.185   2            1.216
LOT_SIZE         1.179   1            1.086
AIR_CONDITIONER  1.395   1            1.181
POOL             1.057   1            1.028
QUALITY          3.817   2            1.398
HIGHWAY          1.032   1            1.016
In [8]:
# ================================================================
# PART 2. RIDGE REGRESSION
# ================================================================

# Ridge regression is a method for reducing the instability
# of regression coefficients caused by multicollinearity.
#
# Ordinary least squares minimizes:
#
#     SSE = sum((Yi - Yhat_i)^2)
#
# Ridge regression minimizes:
#
#     SSE + lambda * sum(beta_j^2)
#
# where the penalty applies to the slopes, not the intercept.
#
# lambda >= 0 controls the amount of shrinkage.
#
# lambda = 0:
#     Ridge regression reduces to ordinary least squares.
#
# Larger lambda:
#     Coefficients are increasingly shrunk toward zero.
#
# Ridge regression generally does not set coefficients
# exactly equal to zero.
#
# IMPORTANT:
# Predictor variables should usually be standardized
# before ridge regression because they may be measured
# on very different scales.
#
# sklearn uses the penalty parameter alpha for lambda.
# Here we will call it lambda in our comments and graphs.


# ------------------------------------------------
# 2A. Standardize the predictors
# ------------------------------------------------

# We again use mtcars, predicting mpg from all
# the other variables.
#
# StandardScaler subtracts each predictor's mean
# and divides by its standard deviation.
#
# This makes the penalty comparable across predictors.

Y = mtcars["mpg"]

X = mtcars.drop(columns="mpg")

scaler = StandardScaler()

Xs = scaler.fit_transform(X)


# ------------------------------------------------
# 2B. Fit ridge regression with lambda = 0.5
# ------------------------------------------------

# Ridge() fits the regression model for a specified
# penalty parameter.
#
# The intercept is not penalized.

rr = Ridge(alpha=0.5)

rr.fit(Xs, Y)


# Display the estimated coefficients.
#
# These are coefficients for standardized predictors.

coef = pd.Series(
    rr.coef_,
    index=X.columns
)

print("\nRIDGE REGRESSION: lambda = 0.5")

print("Intercept:", round(rr.intercept_, 4))

print("\nCoefficients for standardized predictors:")
print(coef.round(4))


# ------------------------------------------------
# 2C. Ridge regression for a range of lambda values
# ------------------------------------------------

# Instead of choosing one lambda, we can fit ridge
# regression for many values.
#
# We will use lambda = 0, 0.1, 0.2, ..., 30.
#
# At lambda = 0, the fitted model is ordinary
# least squares.
#
# As lambda increases, the standardized coefficients
# are gradually shrunk toward zero.


lambdas = np.arange(0, 30.1, 0.1)

coefficients = []

for lam in lambdas:

    rr = Ridge(alpha=lam)

    rr.fit(Xs, Y)

    coefficients.append(rr.coef_)


coefficients = np.array(coefficients)


# ------------------------------------------------
# 2D. Plot the ridge coefficient paths
# ------------------------------------------------

# Each curve shows how one regression coefficient
# changes as lambda increases.
#
# Coefficients are expressed on the standardized
# predictor scale.

plt.figure(figsize=(10, 6))

for j, variable in enumerate(X.columns):

    plt.plot(
        lambdas,
        coefficients[:, j],
        label=variable
    )

plt.axhline(0, color="black", linewidth=0.7)

plt.xlabel("Lambda")
plt.ylabel("Ridge regression coefficient")
plt.title("Ridge Coefficient Paths")

plt.legend()
plt.grid(alpha=0.3)

plt.show()


# ------------------------------------------------
# 2E. Generalized cross-validation (GCV)
# ------------------------------------------------

# We need a method for choosing lambda.
#
# Generalized cross-validation estimates prediction
# error without repeatedly fitting models on
# different training and testing samples.
#
# For ridge regression:
#
#                    SSE(lambda) / n
#     GCV(lambda) = ----------------------
#                    (1 - df(lambda)/n)^2
#
# where df(lambda) is the effective number of
# fitted parameters.
#
# Unlike ordinary least squares, ridge regression
# has a fractional effective degrees of freedom.
#
# Smaller GCV indicates better estimated
# prediction performance.
#
# We standardize the response for this calculation
# to make the GCV values dimensionless.
#
# The following calculation uses the singular values
# of the standardized design matrix.


# Center and standardize the response.

ys = (
    Y.to_numpy() - Y.mean()
) / Y.std(ddof=0)


# Singular value decomposition of Xs.

U, singular_values, Vt = np.linalg.svd(
    Xs,
    full_matrices=False
)


n = len(Y)

GCV = []

for lam in lambdas:

    # Fit ridge regression to the standardized response.

    rr = Ridge(alpha=lam)

    rr.fit(Xs, ys)

    # Sum of squared residuals.

    residuals = ys - rr.predict(Xs)

    SSE = np.sum(residuals ** 2)

    # Effective degrees of freedom for ridge regression.
    #
    # Add 1 for the unpenalized intercept.

    df = 1 + np.sum(
        singular_values ** 2 /
        (singular_values ** 2 + lam)
    )

    # Generalized cross-validation.

    gcv = (SSE / n) / (1 - df / n) ** 2

    GCV.append(gcv)


GCV = np.array(GCV)


# ------------------------------------------------
# 2F. Plot GCV against lambda
# ------------------------------------------------

plt.figure(figsize=(9, 5))

plt.plot(
    lambdas,
    GCV,
    marker=".",
    markersize=3
)

plt.xlabel("Lambda")
plt.ylabel("GCV")
plt.title("Generalized Cross-Validation")

plt.grid(alpha=0.3)

plt.show()


# ------------------------------------------------
# 2G. Find the optimal lambda
# ------------------------------------------------

# Choose the lambda value that minimizes GCV.

lambda_optimal = lambdas[np.argmin(GCV)]

print("\nOPTIMAL LAMBDA")

print("Lambda minimizing GCV:",
      round(lambda_optimal, 3))

print("Minimum GCV:",
      round(GCV.min(), 4))


# ------------------------------------------------
# 2H. Fit the optimal ridge regression model
# ------------------------------------------------

# Fit the ridge regression using the optimal lambda.

rr_optimal = Ridge(alpha=lambda_optimal)

rr_optimal.fit(Xs, Y)


# Display the intercept and coefficients.
#
# The following coefficients are on the standardized
# predictor scale.

print("\nOPTIMAL RIDGE REGRESSION")

print("Intercept:", round(rr_optimal.intercept_, 4))

print("\nCoefficients:")

print(
    pd.Series(
        rr_optimal.coef_,
        index=X.columns
    ).round(4)
)


# ------------------------------------------------
# 2I. Prediction with ridge regression
# ------------------------------------------------

# Ridge regression is still a linear regression model.
#
# Predicted values are calculated by:
#
#     Yhat = beta0 + X * beta
#
# sklearn provides the predict() function, so we
# do not need to perform the matrix multiplication
# manually.
#
# We calculate predicted mpg for the observations
# in the mtcars dataset.


mpg_predicted = rr_optimal.predict(Xs)


# Display observed and predicted values.

prediction_table = pd.DataFrame({
    "Observed mpg": Y,
    "Predicted mpg": mpg_predicted
})

print("\nOBSERVED AND PREDICTED MPG")

print(prediction_table.round(2))


# ------------------------------------------------
# 2J. Plot observed versus predicted mpg
# ------------------------------------------------

# If the predictions were perfect, all points would
# lie on the diagonal line Yhat = Y.
#
# The closer the points are to this line,
# the better the fit to the observed data.

plt.figure(figsize=(7, 6))

plt.scatter(
    Y,
    mpg_predicted
)

limits = [
    min(Y.min(), mpg_predicted.min()),
    max(Y.max(), mpg_predicted.max())
]

plt.plot(
    limits,
    limits,
    "k--"
)

plt.xlabel("Observed mpg")
plt.ylabel("Predicted mpg")
plt.title("Ridge Regression: Observed vs Predicted")

plt.grid(alpha=0.3)

plt.show()


# ------------------------------------------------
# 2K. Calculate predictions using matrix multiplication
# ------------------------------------------------

# To illustrate the linear regression formula,
# we can calculate the same predictions manually.
#
# Ridge.predict() uses:
#
#     Yhat = beta0 + Xs @ beta
#
# where @ denotes matrix multiplication in Python.


mpg_predicted_manual = (
    rr_optimal.intercept_
    + Xs @ rr_optimal.coef_
)


# Verify that both methods give the same predictions.

print("\nMAXIMUM DIFFERENCE BETWEEN PREDICTIONS")

print(
    np.max(
        np.abs(
            mpg_predicted - mpg_predicted_manual
        )
    )
)
RIDGE REGRESSION: lambda = 0.5
Intercept: 20.0906

Coefficients for standardized predictors:
cyl    -0.2224
disp    0.6906
hp     -1.1323
drat    0.4666
wt     -2.7543
qsec    1.0678
vs      0.1692
am      1.1770
gear    0.5036
carb   -0.7514
dtype: float64
No description has been provided for this image
No description has been provided for this image
OPTIMAL LAMBDA
Lambda minimizing GCV: 15.4
Minimum GCV: 0.2127

OPTIMAL RIDGE REGRESSION
Intercept: 20.0906

Coefficients:
cyl    -0.6573
disp   -0.6460
hp     -0.7804
drat    0.5547
wt     -1.1751
qsec    0.2831
vs      0.3851
am      0.7902
gear    0.3946
carb   -0.8621
dtype: float64

OBSERVED AND PREDICTED MPG
                     Observed mpg  Predicted mpg
rownames                                        
Mazda RX4                    21.0          21.93
Mazda RX4 Wag                21.0          21.70
Datsun 710                   22.8          26.21
Hornet 4 Drive               21.4          20.55
Hornet Sportabout            18.7          16.60
Valiant                      18.1          20.27
Duster 360                   14.3          14.42
Merc 240D                    24.4          23.20
Merc 230                     22.8          23.61
Merc 280                     19.2          20.22
Merc 280C                    17.8          20.32
Merc 450SE                   16.4          15.65
Merc 450SL                   17.3          16.10
Merc 450SLC                  15.2          16.10
Cadillac Fleetwood           10.4          12.29
Lincoln Continental          10.4          12.07
Chrysler Imperial            14.7          12.28
Fiat 128                     32.4          27.20
Honda Civic                  30.4          28.30
Toyota Corolla               33.9          27.92
Toyota Corona                21.5          23.84
Dodge Challenger             15.5          16.58
AMC Javelin                  15.2          17.24
Camaro Z28                   13.3          14.62
Pontiac Firebird             19.2          15.82
Fiat X1-9                    27.3          27.43
Porsche 914-2                26.0          25.91
Lotus Europa                 30.4          26.67
Ford Pantera L               15.8          18.28
Ferrari Dino                 19.7          20.08
Maserati Bora                15.0          14.37
Volvo 142E                   21.4          25.12
No description has been provided for this image
MAXIMUM DIFFERENCE BETWEEN PREDICTIONS
0.0
In [ ]:
# ================================================================
# PART 3. EXPORT THE NOTEBOOK TO HTML AND IPYNB
# ================================================================

# The following code saves the current Google Colab
# notebook in TWO formats:
#
#   1. HTML:
#      A readable document containing code, explanations,
#      tables, and graphical output.
#
#   2. IPYNB:
#      The original executable Jupyter notebook.
#      This file can be opened in Google Colab or Jupyter.
#
# Run this section AFTER executing all the previous cells,
# so that the saved notebook contains their output.
#
# Both files will be downloaded to your computer.
#
# By default, the browser saves downloaded files in its
# Downloads folder. The browser's download settings
# determine whether you can choose another folder.


from google.colab import _message, files
from nbconvert import HTMLExporter
import nbformat
import json


# Retrieve the current Google Colab notebook.

notebook = _message.blocking_request(
    "get_ipynb",
    timeout_sec=60
)["ipynb"]


# Convert the notebook into standard Jupyter format.

nb = nbformat.reads(
    notebook if isinstance(notebook, str)
    else json.dumps(notebook),
    as_version=4
)


# Specify a common filename for both versions.

filename = "Py Lab 11 - Multicollinearity and Ridge Regression"


# ------------------------------------------------
# Save the executable Jupyter notebook (.ipynb)
# ------------------------------------------------

with open(filename + ".ipynb", "w", encoding="utf-8") as f:
    nbformat.write(nb, f)


# ------------------------------------------------
# Convert the notebook to HTML
# ------------------------------------------------

html, resources = HTMLExporter().from_notebook_node(nb)


# Save the HTML document.

with open(filename + ".html", "w", encoding="utf-8") as f:
    f.write(html)


# ------------------------------------------------
# Download both files
# ------------------------------------------------

files.download(filename + ".html")

files.download(filename + ".ipynb")


# ================================================================
# END OF LAB 11
# ================================================================
In [ ]: